package com.gree.changying.server;

import android.content.Context;
import android.util.Log;

import com.gree.changying.Const;
import com.gree.changying.server.network.http.HttpException;
import com.gree.changying.server.network.http.RequestParams;
import com.gree.changying.server.network.http.SyncHttpClient;
import com.gree.changying.server.request.UserInfoRequest;
import com.gree.changying.server.response.UserTokenRespone;
import com.gree.changying.server.utils.ErrMsgUtil;
import com.gree.changying.server.utils.LogUtil;
import com.gree.changying.server.utils.SHA256Util;
import com.gree.changying.server.utils.SharedPreferencesUtil;
import com.gree.changying.server.utils.json.JsonMananger;
import com.gree.changying.utils.StringUtil;


import org.apache.http.entity.StringEntity;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.List;


public class BaseAction {

    public static String username ,password;

    /**
     * 生产环境
     *  账号S92198011408 密码S92198011408
     */
    //登录
    public static String DOMAIN_LOGIN = "https://idmshyun.gree.com";
    //手机端
    public static String DOMAIN_FLYDIY = "https://apishyun.gree.com/api/sso/autoapp-default-server-greeshmobile/api";
    //ESB通道
    public static String DOMAIN_FLYDIY_ESB = "https://apishyun.gree.com/api/esb/autoapp-default-server-greeshmobile/api";
    public static String ESB_TOKEY = "eWZwH7jshgrBFEM9wgvZBCUyGJ3XtqXU";
    //文件上传
    public static String DOMAIN_FLYDIY_UPLOAD = "https://apishyun.gree.com/api/sso/nts-foundation-attachmentmanager/api/v2";


    //安装
    public static String DOMAIN_INSTALL= "https://apishyun.gree.com/api/sso/autoapp-default-server-greeshinstall/api";
    //维修
    public static String DOMAIN_REPAIR= "https://apishyun.gree.com/api/sso/autoapp-default-server-greeshservice/api";
    //合并
    public static String DOMAIN_MERGE= "https://apishyun.gree.com/api/sso/autoapp-default-server-greeshmerge/api";

    //消息队列
    public static String DOMAIN_KAFKA= "https://apishyun.gree.com/api/sso/autoapp-default-server-wxkafkaproducer/api";
    //自动派工
    public static String AUTO_RULE="https://apishyun.gree.com/api/sso/autoapp-default-server-greeshautorule/api";

    //greedeliveryjobs
    public static String DOMAIN_DELIVERYJOBS ="https://apishyun.gree.com/api/sso/autoapp-default-server-greedeliveryjobs/api";
    //主数据
    public static String DOMAIN_MASTERDATA= "https://apishyun.gree.com/api/sso/autoapp-default-server-greeshmasterdata/api";
    private final static String CONTENT_TYPE = "application/json";
    private final static String CONTENT_TYPE_2 = "application/x-www-form-urlencoded";
    private final static String ENCODING = "utf-8";

    protected Context mContext;
    protected SyncHttpClient httpManager;

    /**
     * 构造方法
     *
     * @param context 上下文
     */
    public BaseAction(Context context) {
        if(Const.DEVELOPMENT){
            changeEvement();
        }
        this.mContext = context;
        this.httpManager = SyncHttpClient.getInstance(context);
    }
    private static void changeEvement(){
        switch (Const.EVENT){
            case 0:
                DOMAIN_LOGIN = "http://idm.flydiy.gree.com:7393";
                DOMAIN_FLYDIY = "http://gateway.flydiy.gree.com:7393/api/sso/autoapp-default-server-greeshmobile/api/yipai";
                DOMAIN_FLYDIY_ESB = "http://gateway.flydiy.gree.com:7393/api/esb/autoapp-default-server-greeshmobile/api/yipai";
                ESB_TOKEY = "autoappAA3BcOyKTYF5XSyymfFiWBKJkOGvlAAAAX";
                DOMAIN_FLYDIY_UPLOAD = "http://gateway.flydiy.gree.com:7393/api/sso/nts-foundation-attachmentmanager/api/v2";
                //安装
                 DOMAIN_INSTALL= "http://gateway.flydiy.gree.com:7393/api/sso/autoapp-default-server-greeshinstall/api";
                //维修
                DOMAIN_REPAIR= "http://gateway.flydiy.gree.com:7393/api/sso/autoapp-default-server-greeshservice/api";
                //合并
               DOMAIN_MERGE= "http://gateway.flydiy.gree.com:7393/api/sso/autoapp-default-server-greeshmerge/api";

                //消息队列
                DOMAIN_KAFKA= "http://gateway.flydiy.gree.com:7393/api/sso/autoapp-default-server-wxkafkaproducer/api";
                //自动派工
               AUTO_RULE="http://gateway.flydiy.gree.com:7393/api/sso/autoapp-default-server-greeshautorule/api";
                //主数据
                DOMAIN_MASTERDATA= "http://gateway.flydiy.gree.com:7393/api/sso/autoapp-default-server-greeshmasterdata/api";
                DOMAIN_DELIVERYJOBS ="http://gateway.flydiy.gree.com:7393/api/sso/autoapp-default-server-greedeliveryjobs/api";
                break;
            case 1:
                DOMAIN_LOGIN = "http://idm2.flydiy.gree.com:7393";
                DOMAIN_FLYDIY = "http://gateway2.flydiy.gree.com:7393/api/sso/autoapp-default-server-greeshmobile/api/yipai";
                DOMAIN_FLYDIY_ESB = "http://gateway2.flydiy.gree.com:7393/api/esb/autoapp-default-server-greeshmobile/api/yipai";
                ESB_TOKEY = "autoappAA3BcOyKTYF5XSyymfFiWBKJkOGvlAAAAX";
                DOMAIN_FLYDIY_UPLOAD = "http://gateway2.flydiy.gree.com:7393/api/sso/nts-foundation-attachmentmanager/api/v2";
                //安装
               DOMAIN_INSTALL= "http://gateway2.flydiy.gree.com:7393/api/sso/autoapp-default-server-greeshinstall/api";
                //维修
                DOMAIN_REPAIR= "http://gateway2.flydiy.gree.com:7393/api/sso/autoapp-default-server-greeshservice/api";
                //合并
               DOMAIN_MERGE= "http://gateway2.flydiy.gree.com:7393/api/sso/autoapp-default-server-greeshmerge/api";

                //消息队列
                DOMAIN_KAFKA= "http://gateway2.flydiy.gree.com:7393/api/sso/autoapp-default-server-wxkafkaproducer/api";
                //自动派工
                AUTO_RULE="http://gateway2.flydiy.gree.com:7393/api/sso/autoapp-default-server-greeshautorule/api";
                //主数据
                DOMAIN_MASTERDATA= "http://gateway2.flydiy.gree.com:7393/api/sso/autoapp-default-server-greeshmasterdata/api";
                DOMAIN_DELIVERYJOBS ="http://gateway2.flydiy.gree.com:7393/api/sso/autoapp-default-server-greedeliveryjobs/api";
                break;
            case 2:
                break;
        }
    }
    public static void  init(String username, String password){
        BaseAction.username = username;
        BaseAction.password = password;
    }

    protected String token = null;
    //页面在初始化的时候加载token
    public void setToken(String token){
        this.token = token;
    }

    /**
     * JSON转JAVA对象方法
     *
     * @param json json
     * @param cls  class
     * @throws HttpException
     */
    public <T> T jsonToBean(String json, Class<T> cls) throws HttpException {
        return JsonMananger.jsonToBean(json, cls);
    }

    /**
     * JSON转JAVA数组方法
     *
     * @param json json
     * @param cls  class
     * @throws HttpException
     */
    public <T> List<T> jsonToList(String json, Class<T> cls) throws HttpException {
        return JsonMananger.jsonToList(json, cls);
    }

    /**
     * JAVA对象转JSON方法
     *
     * @param obj object
     * @throws HttpException
     */
    public String BeanTojson(Object obj) throws HttpException {
        return JsonMananger.beanToJson(obj);
    }
    /**
     * POST请求
     * 参数直接放在url里
     * @param url
     * @param cla
     * @param obj
     * @param <T>
     * @return
     * @throws HttpException
     */
    public <T>T postWidthParameter(String domain, String url, Class<T> cla, Object obj) throws HttpException {
        url = new StringBuffer(domain).append("/").append(getURL(url,obj)).toString() ;
        return postDo(url,cla,null);
    }

    /**
     * POST请求
     * @param url
     * @param cla
     * @param obj
     * @param <T>
     * @return
     * @throws HttpException
     */
    public <T>T post(String domain, String url, Class<T> cla, Object obj) throws HttpException {
        url = new StringBuffer(domain).append("/").append(getURL(url,null)).toString() ;
        return postDo(url,cla,obj);
    }
    private <T>T postDo(String uri, Class<T> cla, Object obj) throws HttpException {
        String json = BeanTojson(obj);
        StringEntity entity = null;
        try {
            entity = new StringEntity(json, ENCODING);
            entity.setContentType(CONTENT_TYPE);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String result = httpManager.post(mContext, uri, entity, CONTENT_TYPE);
        if(Const.DEBUG) {
            LogUtil.e("postresult", uri +"->"+ result);
        }
        if (!StringUtil.isEmpty(result)) {
            if(result.startsWith("{")&&cla!=null){
                return (T) JsonMananger.jsonToBean(result, cla);
            }else{
                return (T)result;
            }
        }
        return null;
    }

    /**
     * 新平台的请求方式
     * @param domain
     * @param uri
     * @param cla
     * @param obj
     * @param <T>
     * @return
     * @throws HttpException
     */
    public <T>T postWidthParams(String domain, String uri, Class<T> cla, Object obj) throws HttpException {
        String url = new StringBuffer(domain).append("/").append(getURL(uri,null)).toString() ;
        RequestParams params = classToParam(obj);
        if(token!=null) {
            httpManager.addHeader("Authorization","Bearer "+token);
        }
        String result = httpManager.post(mContext, url, params, CONTENT_TYPE_2);
        if(Const.DEBUG) {
            LogUtil.e("postresult", url +"->"+ result);
        }
        if (!StringUtil.isEmpty(result)) {
            if(result.startsWith("{")&&cla!=null){
                return (T) JsonMananger.jsonToBean(result, cla);
            }else{
                return (T)result;
            }
        }
        return null;
    }

    //内网调用
    public <T>T postInESB(String domain, String uri, Class<T> cla, Object obj) throws HttpException {
        String url = new StringBuffer(domain).append("/").append(getURL(uri,null)).toString() ;

        String token = ESB_TOKEY;
        String appname="autoapp";
        String timestamp = System.currentTimeMillis()/1000+"";
        String signature = SHA256Util.getSHA256String(appname+token+timestamp);
        httpManager.removeHeader("Authorization");
        httpManager.addHeader("X-ESB-Timestamp",timestamp);
        httpManager.addHeader("X-ESB-Signature",signature);
        httpManager.addHeader("X-ESB-Appname",appname);
        //NLog.d("dddddd",timestamp);
        //NLog.d("dddddd",signature);
        //NLog.d("dddddd",appname);
        RequestParams params = classToParam(obj);
        //LogUtil.d("dgsdfsdgsd",JsonMananger.beanToJsonStr(params));
        String result = httpManager.post(mContext, url,params , CONTENT_TYPE);
        if(Const.DEBUG) {
           // LogUtil.d("postresult", url +"->"+ result);
        }
        if (!StringUtil.isEmpty(result)) {
            if(result.startsWith("{")&&cla!=null){
                if(result.contains("sys.error")){
                    result = result.replaceAll("\"sys.error\"","null");
                }
                return (T) JsonMananger.jsonToBean(result, cla);
            }else{
                return null;
            }
        }
        return null;
    }

    //esb测试
    public <T>T  postInESBDebug(String domain, String uri, Class<T> cla, Object obj) throws HttpException {
        String url = new StringBuffer(domain).append("/").append(getURL(uri,null)).toString() ;

        String token = "autoappAA3BcOyKTYF5XSyymfFiWBKJkOGvlAAAAX";
        String appname="autoapp";
        String timestamp = System.currentTimeMillis()/1000+"";
        String signature = SHA256Util.getSHA256String(appname+token+timestamp);


        httpManager.removeHeader("Authorization");
        httpManager.addHeader("X-ESB-Timestamp",timestamp);
        httpManager.addHeader("X-ESB-Signature",signature);
        httpManager.addHeader("X-ESB-Appname",appname);
       // NLog.d("dddddd",timestamp);
       // NLog.d("dddddd",signature);
        //NLog.d("dddddd",appname);
        RequestParams params = classToParam(obj);
        //LogUtil.d("dgsdfsdgsd",JsonMananger.beanToJsonStr(params));
        String result = httpManager.post(mContext, url,params , CONTENT_TYPE);
        if(Const.DEBUG) {
            LogUtil.d("postresult", url +"->"+ result);
        }
        if (!StringUtil.isEmpty(result)) {
            if(result.startsWith("{")&&cla!=null){
                if(result.contains("sys.error")){
                    result = result.replaceAll("\"sys.error\"","null");
                }
                return (T) JsonMananger.jsonToBean(result, cla);
            }else{
                return null;
            }
        }
        return null;
    }

    //内网调用
    public <T>T postInFlyESBJSON(String domain, String uri, Class<T> cla, Object obj) throws HttpException {
        String url = new StringBuffer(domain).append("/").append(getURL(uri,null)).toString() ;

        String token = ESB_TOKEY;
        String appname="autoapp";
        String timestamp = System.currentTimeMillis()/1000+"";
        String signature = SHA256Util.getSHA256String(appname+token+timestamp);

        httpManager.removeHeader("token");
        httpManager.addHeader("X-ESB-Timestamp",timestamp);
        httpManager.addHeader("X-ESB-Signature",signature);
        httpManager.addHeader("X-ESB-Appname",appname);
       // NLog.d("dddddd",timestamp);
       // NLog.d("dddddd",signature);
       // NLog.d("dddddd",appname);
        StringEntity params = classToEntity(obj);
        //LogUtil.d("dgsdfsdgsd",JsonMananger.beanToJsonStr(params));
        String result = httpManager.post(mContext, url,params , CONTENT_TYPE);
        if(Const.DEBUG) {
           // LogUtil.d("postresult", url +"->"+ result);
        }
        if (!StringUtil.isEmpty(result)) {
            if(result.startsWith("{")&&cla!=null){
                if(result.contains("sys.error")){
                    result = result.replaceAll("\"sys.error\"","null");
                }
                return (T) JsonMananger.jsonToBean(result, cla);
            }else{
                return null;
            }
        }
        return null;
    }

    /**
     * 获取登录令牌
     * @param userInfo
     * @param <T>
     * @return
     * @throws HttpException
     */
    public <T>T getGreeToken(UserInfoRequest userInfo) throws HttpException {
            if(Const.EVENT==0) {
                //开发 client_id:gree-mobile
                userInfo.setClient_id("gree-mobile");
                return (T) postWidthParams(DOMAIN_LOGIN, "auth/realms/fdp-gree/protocol/openid-connect/token", UserTokenRespone.class, userInfo);
            }else if(Const.EVENT==1) {
                //测试
                userInfo.setClient_id("gree-mobile");
                return (T) postWidthParams(DOMAIN_LOGIN, "auth/realms/fdp2-gree/protocol/openid-connect/token", UserTokenRespone.class, userInfo);
            }else {
                //生产
                userInfo.setClient_id("gree-shyun-mobile");
                return (T)postWidthParams(DOMAIN_LOGIN,"auth/realms/gree-shyun/protocol/openid-connect/token", UserTokenRespone.class,userInfo);
            }
    }

    public <T>T putInFly(String domain, String uri, Class<T> cla, Object obj) throws HttpException {
        token = SharedPreferencesUtil.getData(Const.TOKEN,null);
        Long dates = SharedPreferencesUtil.getData(Const.TOKEN_EXPIRES_TIME,0l);
        if(dates>0){
            Date date = new Date(dates);
            boolean shouldRefresh = SharedPreferencesUtil.getData(Const.SHOULD_REFRESH_TOKEN,false);
            //NLog.e("extend_token",DateUtil.format(date,null),new Date().after(date),"需要强制刷新:"+shouldRefresh);
            if(new Date().after(date)||shouldRefresh){
                SharedPreferencesUtil.putData(Const.SHOULD_REFRESH_TOKEN,false);
                String refresh_token = SharedPreferencesUtil.getData(Const.REFRESH_TOKEN,null);
                //  NLog.e("extend_token","refresh_token",refresh_token);
                UserInfoRequest userInfo = new UserInfoRequest();

                Long refreshdates = SharedPreferencesUtil.getData(Const.REFRESH_TOKEN_EXPIRES_TIME,0l);
                Date refreshdate = new Date(dates);
                if(refreshdates>0&&new Date().after(refreshdate)&&(!StringUtil.isEmpty(username)&&!StringUtil.isEmpty(password))){
                    userInfo.setGrant_type("password");
                    userInfo.setUsername(username);
                    userInfo.setPassword(password);
                }else{
                    userInfo.setGrant_type("refresh_token");
                    userInfo.setRefresh_token(refresh_token);
                }

                UserTokenRespone uToken = getGreeToken(userInfo);
                if(uToken.getError()==null
                        &&uToken.getAccess_token()!=null) {
                    token = uToken.getAccess_token();
                    handleUserToken(uToken);
                }else{
                    return (T) ErrMsgUtil.getMsgRespone(401,"长时间未使用APP导致登录token失效，请重新登录");
                }
            }
        }



        String url = new StringBuffer(domain).append("/").append(getURL(uri,null)).toString() ;

        String json = BeanTojson(obj);
        if(Const.DEBUG) {
            LogUtil.e("putInFly.request", json);
        }
        StringEntity entity = null;
        try {
            entity = new StringEntity(json, ENCODING);
            entity.setContentType(CONTENT_TYPE);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if(token!=null) {
            //LogUtil.e("postInFly.token",token);
            httpManager.addHeader("Authorization","Bearer "+token);
        }
        String result = httpManager.put(mContext, url, entity, CONTENT_TYPE);
        if(Const.DEBUG) {
            // LogUtil.e("postresult", url +"->"+ result);
        }
        if (!StringUtil.isEmpty(result)) {
            if(result.startsWith("{")&&cla!=null){
                if(result.contains("sys.error")){
                    result = result.replaceAll("\"sys.error\"","null");
                }
                return (T) JsonMananger.jsonToBean(result, cla);
            }else{
                return (T)result;
            }
        }
        return null;
    }
    public <T>T postInFly(String domain, String uri, Class<T> cla, Object obj) throws HttpException {
        token = SharedPreferencesUtil.getData(Const.TOKEN,null);
        Long dates = SharedPreferencesUtil.getData(Const.TOKEN_EXPIRES_TIME,0l);
        if(dates>0){
            Date date = new Date(dates);
            boolean shouldRefresh = SharedPreferencesUtil.getData(Const.SHOULD_REFRESH_TOKEN,false);
            //NLog.e("extend_token",DateUtil.format(date,null),new Date().after(date),"需要强制刷新:"+shouldRefresh);
            if(new Date().after(date)||shouldRefresh){
                SharedPreferencesUtil.putData(Const.SHOULD_REFRESH_TOKEN,false);
                String refresh_token = SharedPreferencesUtil.getData(Const.REFRESH_TOKEN,null);
                //  NLog.e("extend_token","refresh_token",refresh_token);
                UserInfoRequest userInfo = new UserInfoRequest();

                Long refreshdates = SharedPreferencesUtil.getData(Const.REFRESH_TOKEN_EXPIRES_TIME,0l);
                Date refreshdate = new Date(dates);
                if(refreshdates>0&&new Date().after(refreshdate)&&(!StringUtil.isEmpty(username)&&!StringUtil.isEmpty(password))){
                    userInfo.setGrant_type("password");
                    userInfo.setUsername(username);
                    userInfo.setPassword(password);
                }else{
                    userInfo.setGrant_type("refresh_token");
                    userInfo.setRefresh_token(refresh_token);
                }

                UserTokenRespone uToken = getGreeToken(userInfo);
                if(uToken.getError()==null
                        &&uToken.getAccess_token()!=null) {
                    token = uToken.getAccess_token();
                    handleUserToken(uToken);
                }else{
                    return (T) ErrMsgUtil.getMsgRespone(401,"长时间未使用APP导致登录token失效，请重新登录");
                }
            }
        }



        String url = new StringBuffer(domain).append("/").append(getURL(uri,null)).toString() ;

        String json = BeanTojson(obj);
        if(Const.DEBUG) {
            LogUtil.e("postInFly.request", json);
        }
        StringEntity entity = null;
        try {
            entity = new StringEntity(json, ENCODING);
            entity.setContentType(CONTENT_TYPE);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if(token!=null) {
            //LogUtil.e("postInFly.token",token);
            httpManager.addHeader("Authorization","Bearer "+token);
        }
        String result = httpManager.post(mContext, url, entity, CONTENT_TYPE);
        if(Const.DEBUG) {
           // LogUtil.e("postresult", url +"->"+ result);
        }
        if (!StringUtil.isEmpty(result)) {
            if(result.startsWith("{")&&cla!=null){
                if(result.contains("sys.error")){
                    result = result.replaceAll("\"sys.error\"","null");
                }
                return (T) JsonMananger.jsonToBean(result, cla);
            }else{
                return (T)result;
            }
        }
        return null;
    }

    //处理usertoken
    private void handleUserToken(UserTokenRespone uToken){
        SharedPreferencesUtil.putData(Const.TOKEN, token);
        SharedPreferencesUtil.putData(Const.REFRESH_TOKEN, uToken.getRefresh_token());
        SharedPreferencesUtil.putData(Const.REFRESH_TOKEN_EXPIRES, uToken.getRefresh_expires_in());
        SharedPreferencesUtil.putData(Const.TOKEN_EXPIRES, uToken.getExpires_in());
        Date thisDate = new Date();
        int expirs_token = Integer.parseInt(uToken.getExpires_in()) * 1000 - 60 * 1000;
        Date expires = new Date(thisDate.getTime() + expirs_token);
        // NLog.e("extend_token", "token过期时间:" + DateUtil.format(expires, null), expires.getTime());
        SharedPreferencesUtil.putData(Const.TOKEN_EXPIRES_TIME, expires.getTime());
    }

    public <T>T getInFly(String domain, String uri, Class<T> cla, Object obj) throws HttpException {
        token = SharedPreferencesUtil.getData(Const.TOKEN,null);
        Long dates = SharedPreferencesUtil.getData(Const.TOKEN_EXPIRES_TIME,0l);
        if(dates>0){
            Date date = new Date(dates);
            boolean shouldRefresh = SharedPreferencesUtil.getData(Const.SHOULD_REFRESH_TOKEN,false);
            //NLog.e("extend_token",DateUtil.format(date,null),new Date().after(date),"需要强制刷新:"+shouldRefresh);
            if(new Date().after(date)||shouldRefresh){
                SharedPreferencesUtil.putData(Const.SHOULD_REFRESH_TOKEN,false);
                String refresh_token = SharedPreferencesUtil.getData(Const.REFRESH_TOKEN,null);
              //  NLog.e("extend_token","refresh_token",refresh_token);
                UserInfoRequest userInfo = new UserInfoRequest();

                Long refreshdates = SharedPreferencesUtil.getData(Const.REFRESH_TOKEN_EXPIRES_TIME,0l);
                Date refreshdate = new Date(dates);
                if(refreshdates>0&&new Date().after(refreshdate)&&(!StringUtil.isEmpty(username)&&!StringUtil.isEmpty(password))){
                    userInfo.setGrant_type("password");
                    userInfo.setUsername(username);
                    userInfo.setPassword(password);
                }else{
                    userInfo.setGrant_type("refresh_token");
                    userInfo.setRefresh_token(refresh_token);
                }

                UserTokenRespone uToken = getGreeToken(userInfo);
                if(uToken.getError()==null
                        &&uToken.getAccess_token()!=null) {
                    token = uToken.getAccess_token();
                    handleUserToken(uToken);
                }else{
                    return (T) ErrMsgUtil.getMsgRespone(401,"长时间未使用APP导致登录token失效，请重新登录");
                }
            }
        }



        String url = new StringBuffer(domain).append("/").append(getURL(uri,null)).toString() ;

        RequestParams params = classToParam(obj);
      //  NLog.e("getInFly.request",JsonMananger.beanToJsonStr(params));

        if(token!=null) {
           // LogUtil.e("getInFly.token",token);
            httpManager.addHeader("Authorization","Bearer "+token);
        }
        String result = httpManager.get(mContext, url, params);
        if(Const.DEBUG) {
         //   LogUtil.e("getresult", url +"->"+ result);
        }
        if (!StringUtil.isEmpty(result)) {
            if(result.startsWith("{")&&cla!=null){
                if(result.contains("sys.error")){
                    result = result.replaceAll("\"sys.error\"","null");
                }
                return (T) JsonMananger.jsonToBean(result, cla);
            }else{
                return null;
            }
        }
        return null;
    }

    /**
     * GET
     * @param url
     * @param cla
     * @param <T>
     * @return
     * @throws HttpException
     */
    public <T>T get(String domain, String url, Class<T> cla) throws HttpException {
        return get(domain,url,cla,null);
    }
    /**
     * GET请求
     * @param url
     * @param cla
     * @param obj
     * @param <T>
     * @return
     * @throws HttpException
     */
    public <T>T get(String domain, String url, Class<T> cla, Object obj) throws HttpException {
        url = new StringBuffer(domain).append("/").append(getURL(url,obj)).toString() ;
        String result =  httpManager.get(mContext,url);
        if(Const.DEBUG) {
           // Log.e("getresult", url +"->"+ result);
        }
        if (!StringUtil.isEmpty(result)) {
            if(result.startsWith("{")&&cla!=null){
                return (T) JsonMananger.jsonToBean(result, cla);
            }else{
                return (T)result;
            }
        }
        return null;
    }

    /**
     * delete
     * @param url
     * @param cla
     * @param <T>
     * @return
     * @throws HttpException
     */
    public <T>T delete(String domain, String url, Class<T> cla) throws HttpException {
        return delete(domain,url,cla,null);
    }
    /**
     * delete请求
     * @param url
     * @param cla
     * @param obj
     * @param <T>
     * @return
     * @throws HttpException
     */
    public <T>T delete(String domain, String url, Class<T> cla, Object obj) throws HttpException {
        url = new StringBuffer(domain).append("/").append(getURL(url,obj)).toString() ;
        String result =  httpManager.delete(mContext,url);
        if(Const.DEBUG) {
            Log.e("deleteresult", url +"->"+ result);
        }
        if (!StringUtil.isEmpty(result)) {
            if(result.startsWith("{")&&cla!=null){
                return (T) JsonMananger.jsonToBean(result, cla);
            }else{
                return (T)result;
            }
        }
        return null;
    }


    /**
     * 文件上传
     * @param url
     * @param cla
     * @param obj
     * @param <T>
     * @return
     */
    public <T>T upload(String domain, String url, Class<T> cla, Object obj, String filepath) throws HttpException {
        url = new StringBuffer(domain).append("/").append(getURL(url,null)).toString() ;
        if(Const.DEBUG) {
            Log.e("uploadfilepath",  "->"+ filepath);
        }
        File file = new File(filepath);
        if(file.isFile()){
            try {
                RequestParams params = new RequestParams();
                params.put("file",file);
                params.put("size",file.length());
                if(obj!=null){
                    Class<?> c = obj.getClass();
                    Field[] fa =  c.getDeclaredFields();;
                    for(Field f:fa){
                        f.setAccessible(true);
                        try {
                            params.put(f.getName(), String.valueOf(f.get(obj)));
                        }catch (Exception e){

                        }
                    }
                }
                String result = httpManager.post(mContext,url,params);
                if(Const.DEBUG) {
                    Log.e("uploadresult", url +"->"+ result);
                }
                if (!StringUtil.isEmpty(result)) {
                    if(result.startsWith("{")&&cla!=null){
                        return (T) JsonMananger.jsonToBean(result, cla);
                    }else{
                        return (T)result;
                    }
                }
            }catch (IOException e){
                Log.e("uploadIOException",e.getMessage());
                e.printStackTrace();
            }
        }
        return null;
    }
    /**
     * 获取完整URL属性值
     * @param url
     * @param obj
     * @return
     */
    protected static String getURL(String url, Object obj) {
        StringBuilder urlBuilder = new StringBuilder(url);
        if(obj!=null){
            urlBuilder.append("?");
            Class<?> cla = obj.getClass();
            Field[] fa =  cla.getDeclaredFields();;
            int i = 0 ;
            for(Field f:fa){
                f.setAccessible(true);

                try {
                    Object val = f.get(obj);
                    if(val!=null) {
                        String name = f.getName();
                        //_ -> [0]
                       //name = name.replaceAll("_", "[0]");
                        //$ -> .
                        //name = name.replaceAll("$", ".");
                        urlBuilder.append(name + "=" + val);
                        if (i < fa.length - 1) {
                            urlBuilder.append("&");
                        }
                    }
                }catch (Exception e){

                }
                i++;
            }
        }
        return urlBuilder.toString();
    }

    public static RequestParams classToParam(Object obj){
        RequestParams params = new RequestParams();
        if(obj==null){
            return params;
        }
       // NLog.e("classToParam", JsonMananger.beanToJsonStr(obj));
        Class<?> cla = obj.getClass();
        Field[] fa =  cla.getDeclaredFields();;
        int i = 0 ;
        for(Field f:fa){
            f.setAccessible(true);
            try {
                Object val = f.get(obj);
                if(val!=null) {
                    params.put(f.getName(),val);
                }
            }catch (Exception e){

            }
        }
        return params;
    }
    public static StringEntity classToEntity(Object obj){
        try {
            String json = JsonMananger.beanToJson(obj);
            StringEntity entity = null;
            entity = new StringEntity(json, ENCODING);
            entity.setContentType(CONTENT_TYPE);
            return entity;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
